<template>
  <view class="share_layout_box">
    <canvas class="myCanvas test" :style="'width:'+myCanvasWidth+'px;height:'+myCanvasHeight+'px'" canvas-id="sharePostersWhiteId"></canvas>
  </view>
</template>
<script>
// let canvasData = { // 图片生成参数
//   userAvatar: 'https://image.qqpyyds.com/user/avatar/1448144136114941954', // 用户头像
//   userNickname: '廖志林',  // 用户昵称
//   ranking: 'NO.6', // 排名
//   viewsOfText: 'scajc ',
//   copyText1: '111',
//   bgImgUrl: 'https://image.qqpyyds.com/uni_app/user/163549354120386.png', // 封面大图片
//   title: '这里是动态标题最多两行这里是动态标题最多两行这里是动态标题最这里是动态多这里是动态题最多两题最多两题最多两', // 标题
//   page: '/pages/index/index', // 二维码地址
// }
// import { writeFile, removeSave } from '@/api/baseConvert'
import share from "@/api/share.js"
import canvasUtils from './canvasUtils'
export default {
  data () {
    return {
      myCanvasWidth: 280,
      myCanvasHeight: 532,
      dpiMun: 3,
    }
  },
  created () {
    this.myCanvasWidth = this.myCanvasWidth*this.dpiMun
    this.myCanvasHeight = this.myCanvasHeight*this.dpiMun
  },
  methods: {
    async shareWhitePoster(data) {
      let _this = this
      let _data = data
      let paramMap = {}
      paramMap = {
        page: _data?.page ?? 'pages/index/index',
        ..._data.options
      }
      share.getSunCode(paramMap).then(async (res_) => {
        if (res_.code == 200) {
          let pam = {
            ..._data,
            QRCode: res_.data,
          }
          await _this.createdCode(pam)
          let shareData = {}
          wx.canvasToTempFilePath({
            canvasId: 'sharePostersWhiteId',
            fileType: 'jpg',
            width: _this.myCanvasWidth,
            height: _this.myCanvasHeight,
            destWidth: _this.myCanvasWidth * 2,
            destHeight: _this.myCanvasHeight * 2,
            success: async (res) => {
              shareData = {
                code: '200',
                msg: '绘制成功！',
                shareType: data.type,
                url: res.tempFilePath
              }
              console.log(shareData,'绘制成功')
              if (shareData.code == 200) {
                _this.$emit('drawWhiteShareCardFn', shareData)
              }
              _this.$store.commit('POSTER_SHARING_DATA', shareData)
            },
            fail: function (res) {
              console.log('绘制失败')
            }
          },_this)
          // removeSave() // 先删除在添加
          // writeFile(res_.data).then(async (img)=>{
          // }).catch(e=>{
          //   console.log(e)
          // })
        }
      })
    },
    // 开始绘图
    createdCode (data) {
      const _this = this
      let fromData = data
      return new Promise(resolve => {
        exec()
        async function exec () {
          const ctx = wx.createCanvasContext('sharePostersWhiteId', _this) // 绘图上下文
          ctx.setFillStyle('#ffffff')
          ctx.fillRect(0, 0, _this.myCanvasWidth, _this.myCanvasHeight)
          ctx.save()
          _this.handleBorderRect(ctx, 0, 0, _this.myCanvasWidth, _this.myCanvasHeight, 8*_this.dpiMun,'#ffffff')
          ctx.clip()
          if (fromData.bgImgUrl) {
            let bgImgUrl = fromData.bgImgUrl
            bgImgUrl = bgImgUrl+`?x-oss-process=image/resize,h_${350*_this.dpiMun},w_${_this.myCanvasWidth},m_fill/auto-orient,1/quality,q_90/format,jpg`
            await canvasUtils.drawCoverImage(bgImgUrl, ctx, 0, 0, _this.myCanvasWidth, 350*_this.dpiMun)
            // 视频流显示播放按钮
            if (!fromData.isGoods) {
              await _this.drawImg('https://image.qqpyyds.com/mpAppImg/icon/play3_icon.png', ctx, _this.myCanvasWidth/2-21*_this.dpiMun, (350/2-21)*_this.dpiMun, 42*_this.dpiMun, 42*_this.dpiMun)
            }
          }
          await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/share_name_bg.png', ctx, 0, 0, _this.myCanvasWidth, 40*_this.dpiMun)
          ctx.restore()
          ctx.save()
          ctx.beginPath()
          ctx.strokeStyle = '#fff'
          ctx.arc(30*_this.dpiMun,38*_this.dpiMun,14*_this.dpiMun,0,2*Math.PI)
          ctx.fill()
          ctx.clip()
          await _this.drawImg(fromData.userAvatar, ctx, 16*_this.dpiMun, 24*_this.dpiMun, 28*_this.dpiMun, 28*_this.dpiMun)
          ctx.restore()
          ctx.setFontSize(12*_this.dpiMun)
          ctx.setFillStyle('#fff')
          ctx.fillText(fromData.userNickname, 52*_this.dpiMun, 40.55*_this.dpiMun, 140*_this.dpiMun)
          let followGroup = fromData.viewsOfText || '一大波人赶来中'
          await _this.drawImg('https://qqposs.oss-cn-shenzhen.aliyuncs.com/mpAppImg/other/heat_icon.png', ctx, _this.myCanvasWidth-ctx.measureText(followGroup).width-10*_this.dpiMun, 30*_this.dpiMun, 12*_this.dpiMun, 12*_this.dpiMun)
          ctx.setFontSize(10*_this.dpiMun)
          ctx.setFillStyle('#ffffff')
          ctx.fillText(followGroup, _this.myCanvasWidth-ctx.measureText(followGroup).width-10*_this.dpiMun, 40*_this.dpiMun, 160*_this.dpiMun)
          if (fromData.title) {
            ctx.setFontSize(14*_this.dpiMun)
            ctx.setFillStyle('#323232')
            // let titleStr = fromData.title.length>32?fromData.title.slice(0,31)+'...':fromData.title.slice(0,31)
            await canvasUtils.drawText(ctx, fromData.title, 12*_this.dpiMun, 376*_this.dpiMun, 20*_this.dpiMun, 256*_this.dpiMun)
            // _this.wordsWrap(ctx, titleStr, ctx.measureText(titleStr).width, 256*_this.dpiMun, 12*_this.dpiMun, 376*_this.dpiMun, 20*_this.dpiMun)
          }
          let salePriceStr = `¥${fromData.minSalePrice}`
          if (fromData.minSalePrice != fromData.maxSalePrice) {
            salePriceStr = `¥${fromData.minSalePrice}~${fromData.maxSalePrice}`
          }
          await _this.drawImg(fromData.QRCode, ctx, 180*_this.dpiMun, 420*_this.dpiMun, 80*_this.dpiMun, 80*_this.dpiMun)
          ctx.setFontSize(18*_this.dpiMun)
          ctx.setFillStyle('#E44435')
          ctx.fillText(salePriceStr, 12*_this.dpiMun, 453*_this.dpiMun, 140*_this.dpiMun)
          ctx.restore()
          ctx.save()
          _this.handleBorderRect(ctx, 12*_this.dpiMun, 477*_this.dpiMun, 148*_this.dpiMun, 22*_this.dpiMun, 4*_this.dpiMun, '#F7F8FA')
          ctx.clip()
          ctx.restore()
          let btnTextStr = fromData.copyText2+' >>>'
          ctx.setFontSize(10*_this.dpiMun)
          ctx.setFillStyle('#969799')
          ctx.fillText(btnTextStr, 20*_this.dpiMun, 491*_this.dpiMun, 148*_this.dpiMun)
          ctx.restore()
          ctx.draw(false, () => {
            resolve()
          })
        }
      })
    },
    // 画4个圆角
    handleBorderRect (ctx, x, y, w, h, r, color) {
      ctx.beginPath()
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, 1.5 * Math.PI)
      ctx.moveTo(x + r, y)
      ctx.lineTo(x + w - r, y)
      ctx.lineTo(x + w, y + r)
      // 右上角
      ctx.arc(x + w - r, y + r, r, 1.5 * Math.PI, 2 * Math.PI)
      ctx.lineTo(x + w, y + h - r)
      ctx.lineTo(x + w - r, y + h)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, 0.5 * Math.PI);
      ctx.lineTo(x + r, y + h)
      ctx.lineTo(x, y + h - r)
      // 左下角
      ctx.arc(x + r, y + h - r, r, 0.5 * Math.PI, Math.PI)
      ctx.lineTo(x, y + r)
      ctx.lineTo(x + r, y)
      ctx.fillStyle = color
      ctx.fill()
      ctx.closePath()
    },
    // 文字自动换行
    wordsWrap (ctx, name, nameWidth, maxWidth, startX, srartY, wordsHight) {
      let lineWidth = 0
      let lastSubStrIndex = 0
      for (let i = 0; i < name.length; i++) {
        lineWidth += ctx.measureText(name[i]).width
        if (lineWidth > maxWidth) {
          ctx.fillText(name.substring(lastSubStrIndex, i), startX, srartY)
          srartY += wordsHight
          lineWidth = 0
          lastSubStrIndex = i
        }
        if (i === name.length - 1) {
          ctx.fillText(name.substring(lastSubStrIndex, i + 1), startX, srartY)
        }
      }
    },
    // 绘制远程网络图片
    async drawImg (url, ctx, startX, startY, width, height) {
      let _this = this
      return new Promise(resolve => {
        exec()
        async function exec () {
          wx.getImageInfo({
            src: url,
            success: function (res) {
              const filePath = res.path
              ctx.drawImage(filePath, startX, startY, width, height)
              resolve()
            },
            fail: function (err) {
              console.log(err, url)
            },
            complete: function (err) {
              console.log(err)
            }
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.share_layout_box {
  position: fixed;
  left: -1000px;
  top: -1000px;
  // z-index: 999;
}
</style>